<script setup lang='ts'>
import { useGetMemberDetail, useMemberUpdate } from '@fl/api/member-api/member'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'

const { query } = useRoute()
const { go } = useRouter()

const params = computed(() => {
    return {
        memberOrderId: query?.memberOrderId ?? '',
    }
})
const { data, isLoading } = useGetMemberDetail(params)

const formRef = ref()
const active = ref()

const initialState = {
    memberLevelId: 0,
    // memberOrderId: 0, // 会员申请单Id
    // orderType: 0, // 申请单类型 1 新购会员 2 续费会员
    payAmount: '',
    payDate: '',
    paymentVoucherList: [],
}
const state = ref<any>(cloneDeep(initialState))

const columns: any[] = [
    {
        colProps: {
            span: 8,
        },
        label: '缴费金额(元)',
        labelWidth: '120px',
        prop: 'payAmount',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            valueFormat: 'YYYY-MM-DD',
        },
        label: '缴费日期',
        prop: 'payDate',
        valueType: 'date-picker',
    },
    {
        colProps: {
            span: 12,
        },
        label: '缴费凭证',
        labelWidth: '120px',
        prop: 'paymentVoucherList',

    },
]
function validatorPay(rule, value, callback) {
    const reg = /^\d+$/
    console.log(rule)
    if (!value) {
        callback(new Error('请输入缴费金额'))
        return
    }

    if (!reg.test(value)) {
        callback(new Error('请输入数字'))
        return
    }

    callback()
}

const rules = {
    payAmount: [{ required: true, validator: validatorPay }],
    payDate: [{ message: '请选择缴费日期', required: true }],
    paymentVoucherList: [{ message: '请上传缴费凭证', required: true }],
}

const info = ref<any>({})

const infoCol = [
    {
        colProps: {
            span: 24,
        },
        label: '账户信息',
        valueType: 'text',
    },
    {
        colProps: {
            span: 24,
        },
        label: '收款账户号码',
        prop: 'accountNo',
        valueType: 'text',
    },
    {
        colProps: {
            span: 24,
        },
        label: '收款账户名',
        prop: 'accountName',
        valueType: 'text',
    },
    {
        colProps: {
            span: 24,
        },
        label: '收款银行名称',
        prop: 'bankName',
        valueType: 'text',
    },
    {
        colProps: {
            span: 24,
        },
        label: '收款开户行名称',
        prop: 'branchBank',
        valueType: 'text',
    },
    {
        colProps: {
            span: 24,
        },
        label: '收款开户行地址',
        prop: 'branchBankAddr',
        valueType: 'text',
    },
]

function doClick(item: any) {
    active.value = item.id

    state.value.memberLevelId = item.id
}

function doBack() {
    // push('member')
    go(-1)
}

const { mutate } = useMemberUpdate()
async function doSubmit() {
    if (!state.value.memberLevelId) {
        ElMessage.error('请选择会员类型')
        return
    }

    const valid = await formRef.value.formInstance.formInstance.validate()
    if (!valid)
        return

    const source = window.sessionStorage.getItem('MEMBER_SOURCE')
    const paymentVoucherList = state.value.paymentVoucherList.map((v: any) => {
        return {
            paymentReceipt: v.url,
            receiptName: v.name,
        }
    })
    const params = {
        ...state.value,
        accountNo: info.value.accountNo,
        orderType: query.orderType,
        paymentVoucherList,
        source, // 申请单来源 1后台录入 2集采商城 3招投标
    }

    if (query?.memberOrderId) {
        params.memberOrderId = query.memberOrderId
    }

    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功，请等待审核通过')
            doBack()
        },
    })
}

function doCopy() {
    navigator.clipboard.writeText(info.value.accountNo).then(() => {
        ElMessage.success('复制成功')
    }).catch((err) => {
        // 复制失败
        console.error('复制失败', err)
    })
}

function init(val: any) {
    const { memberLevelId, payAmount, payDate } = val
    const paymentVoucherList = val.paymentVoucherList.map((v: any) => {
        return {
            name: v.receiptName,
            url: v.paymentReceipt,
        }
    })
    state.value = {
        ...state.value,
        memberLevelId,
        payAmount,
        payDate,
        paymentVoucherList,
    }

    active.value = memberLevelId
}

watchEffect(() => {
    if (data.value) {
        info.value = data.value.sysBankAccountVO

        if (data.value?.memberOrderPayInfo) {
            // 详情回显
            init(data.value?.memberOrderPayInfo)
        }
    }
})
</script>

<template>
    <ElCard class="mb-20">
        <p class="text-20 c-#000 font-600">
            {{ query.orderType === '1' ? '会员开通' : '会员续费' }}
        </p>
    </ElCard>

    <ElCard class="mb-20">
        <p class="title">
            会员类型
        </p>

        <div class="flex">
            <div v-for="(item, index) in data?.memberLevelVOList"
                 :key="index"
                 class="pt-30 mb-20 mr-20 border-1 border-gray rounded-4 text-center h-105 w-200 cursor-pointer float-left"
                 :class="{ 'active-sty': active === item.id }"
                 @click="doClick(item)"
            >
                <p>{{ item.levelName }}</p>

                <p>{{ item.priceDate }}</p>
            </div>
        </div>
    </ElCard>

    <ElCard class="mb-20">
        <p class="title">
            缴费信息
        </p>

        <SearchForm ref="formRef"
                    v-model="state"
                    :rules="rules"
                    :columns="columns"
                    :has-footer="false"
        >
            <template #plus-field-paymentVoucherList>
                <FlUpload :key="String(isLoading)"
                          v-model="state.paymentVoucherList"
                          list-type="text"
                          accept=".png,.jpg,.jpeg,.pdf"
                          :limit="5"
                          :file-size="20"
                          tips
                />
            </template>
        </SearchForm>
    </ElCard>

    <ElCard class="mb-20">
        <p class="title flex justify-between">
            <span>收款账号信息</span>

            <ElButton @click="doCopy">
                复制账户信息
            </ElButton>
        </p>

        <p class="mb-20">
            {{ info?.affirmation }}
        </p>

        <SearchForm v-model="info"
                    :label-width="120"
                    :columns="infoCol"
                    :has-footer="false"
        />
    </ElCard>

    <div class="text-center">
        <ElButton class="mr-10"
                  @click="doBack"
        >
            上一步
        </ElButton>

        <ElButton type="primary"
                  @click="doSubmit"
        >
            提交
        </ElButton>
    </div>
</template>

<style lang="less" scoped>
.title {
    font-size: 18px;
    font-weight: 600;
    color: #000;
    margin-bottom: 10px;
}

.active-sty {
    border-color: red;
}
</style>
